package ru.gr.alphaversion;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

public class ItemDescription extends ActivityGroup implements OnClickListener {
	
	public EditText QuantityItem;
	public String value;
	public TextView Description;
	public TextView Price, Code;
	public String id_item;
	public String price_item;
	public String qua_item, fot_item;
	public TextView Qua;
	public static String act, cat_id;
	private ImageView imgView;
	final int PROGRESS_DLG_ID = 666;
	final static String DEBUG_TAG = "+++ImageDownloader+++";
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                setContentView(R.layout.item_description);
        
                
        //value = getIntent().getExtras().getString("ItemId");
        Description = (TextView)findViewById(R.id.item_description);
        Price = (TextView)findViewById(R.id.item_price);
        Qua = (TextView)findViewById(R.id.item_qua);
        QuantityItem = (EditText)findViewById(R.id.quantity_of_item);
        Code = (TextView)findViewById(R.id.item_idd);
        //QuantityItem.setText("1");
        View addButton = findViewById(R.id.add_list_item);
        addButton.setOnClickListener(this);
        //View backButton = findViewById(R.id.back_button_da);
        //backButton.setOnClickListener(this);
        Main.checkk = 1;
        
    
		
		imgView = (ImageView) findViewById(R.id.imageView1);

		// загружаем картинку с указанного адреса в ImageView
		
	
		

	
        Description.setText(getIntent().getExtras().getString("desc"));
        Code.setText("Код: "+getIntent().getExtras().getString("ItemId"));
        Price.setText("Цена за шт: "+getIntent().getExtras().getString("price_item"));
        Qua.setText("Остаток: "+getIntent().getExtras().getString("qua_item"));
        id_item = getIntent().getExtras().getString("ItemId");
        cat_id = getIntent().getExtras().getString("cat_id");
		price_item = getIntent().getExtras().getString("price_item");
		fot_item = getIntent().getExtras().getString("fot_item");
		act = getIntent().getExtras().getString("act");
		
		String PICT_URL = "http://giperbaza.ru/shop/img/nophoto.jpg";
        
         
		
		if (fot_item != "null")
		{
			PICT_URL = "http://giperbaza.ru"+fot_item;
		}
				
		try {
			new DownloadImageTask().execute(PICT_URL);
		} catch (Exception e) {
			System.out.println("Ошибка: Exception");
		}
		if(act==null)
			act="0";
		if(act=="1") {
		Main.checkk = 2;
		}
		if(act=="3") {
			Main.checkk = 3;
			}
        //getDescription(value);
	}
	
	 protected void onPause() {
	    super.onPause();
	    		System.out.println("descpause");
	}
	 
	 protected void onResume() {
		 super.onResume();
			System.out.println("descresume");
		 
	 }
	 
	 
	 protected void onDestroy() {
		 super.onDestroy();
			System.out.println("descdestroy");
		 
	 }
	 
	/* private Drawable grabImageFromUrl(String url) throws Exception {
			return Drawable.createFromStream(
					(InputStream) new URL(url).getContent(), "src");
			
		}*/
	
	    
	   // @Override
	//    public void onCreate(Bundle savedInstanceState){
	  //      super.onCreate(savedInstanceState);
	   //     setContentView(R.layout.tmain);
	        
	    //    loadViews();
	 //   }
	    
	  /*  private void loadViews(){
	       // runButt = (Button)findViewById(R.id.runButt);
	        image =(ImageView)findViewById(R.id.imageView1);
	    }*/
	    
	//    @Override
	/*    protected Dialog onCreateDialog(int dialogId){
	        ProgressDialog progress = null;
	        switch (dialogId) {
	        case PROGRESS_DLG_ID:
	            progress = new ProgressDialog(this);
	                progress.setMessage("Загрузка...");
	            
	            break;
	        }
	        return progress;
	    }*/
	    
	 /*   public void runButtonHandler(View button){
	        if(button.getId() == R.id.runButt)
	            
	    }*/
	    
	    class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
	        @Override
	        protected Bitmap doInBackground(String... params) {
	            publishProgress(new Void[]{});
	            
	            String url = "";
	            if( params.length > 0 ){
	            	url = params[0];		    	
	            }
	           
	            InputStream input = null;
	            
	            try {
	            	URL urlConn = new URL(url);
	                input = urlConn.openStream();
	            }
	            catch (MalformedURLException e) {
	            	Log.d(DEBUG_TAG,"Oops, Something wrong with URL...");
	            	e.printStackTrace();
	            }
	            catch (IOException e) {
	            	Log.d(DEBUG_TAG,"Oops, Something wrong with input stream...");
	                e.printStackTrace();
	            }
	            
	            return BitmapFactory.decodeStream(input);
	        }
	        
	      //  @Override
	       /* protected void onProgressUpdate(Void... values) {
	            super.onProgressUpdate(values);
	            showDialog(PROGRESS_DLG_ID);
	        }*/
	        
	 //       @Override
	        protected void onPostExecute(Bitmap result) {
	            super.onPostExecute(result);
	           // dismissDialog(PROGRESS_DLG_ID);
	            imgView.setImageBitmap(result);	
	        }
	    }
	
	public void onClick(View v) {
		 
		switch (v.getId()) {
    	case R.id.add_list_item:
    		//Toast.makeText(this, "))", Toast.LENGTH_LONG).show();
    		//ItemList newItem = new ItemList();
    		//newItem.getCLtovars(Description.getText().toString());
    		//Intent news = new Intent(this, ItemList.class);
    		//startActivityForResult(news, 3);
    		//TabHost tabHost = Main.self.getTabHost();
    		//tabHost.setCurrentTab(1);
    		//((Main)getParent()).getTabHost().setCurrentTab(1);
    		if (Finder.isNumeric((QuantityItem.getText().toString())))
    				{
    			
    		
    		if (!(QuantityItem.getText().toString().equals(null))){
    		if (Integer.parseInt(QuantityItem.getText().toString())<=Double.parseDouble(getIntent().getExtras().getString("qua_item")))
    		{
    			GetJSON json = new GetJSON();
    			String id_list_item = "";
    			try {
    					String gg = json.postData(id_item, "", "QAddItem", QuantityItem.getText().toString(), this);
    					JSONObject jsonObject = new JSONObject(gg);
    					if(jsonObject.getString("error").equals("1")) {
    						Toast toast = Toast.makeText(this, "Нет товара с таким кодом", Toast.LENGTH_LONG);
    	        			toast.setGravity(Gravity.CENTER, 0, 0);
    	        			toast.show();
    					} else {
    					id_list_item = jsonObject.getString("id");
    			
    			
    					if (Main.list_id == null)
    					{
    						Toast toast = Toast.makeText(this, "Нет активного заказа", Toast.LENGTH_LONG);
    						toast.setGravity(Gravity.CENTER, 0, 0);
    						toast.show();
        			//Toast.makeText(this, QuantityItem.getText().toString()+"   "+getIntent().getExtras().getString("qua_item"), Toast.LENGTH_LONG).show();
    					} else {
    							Main mn = new Main();
    							mn.addItem(id_list_item, Description.getText().toString(), QuantityItem.getText().toString(), price_item, id_item);
    							mn.orderItemList();
    							if(act!="1")
    								{
    									if(!act.equals("3"))
    										{
    											Intent itemfind_ok = new Intent(this, Finder.class);
    												Finder parentActivity_ok = (Finder)getParent();
    												parentActivity_ok.replaceContentView("find_ok", itemfind_ok);
    										}
    										else
    										{
    											Intent itemfind_ok = new Intent(this, Cats.class);
    											Cats parentActivity_ok = (Cats)getParent();
    					
    											parentActivity_ok.replaceContentView("find_ok", itemfind_ok);
    					
    											Main.tabHost.setCurrentTab(3);
    										}
    								} 
    								else
    								{
    				
    									Intent itemfind_ok = new Intent(this, Finder.class);
    									Finder parentActivity_ok = (Finder)getParent();
    									parentActivity_ok.replaceContentView("find_ok", itemfind_ok);
    				
    								}
    						}
    					}
    					} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    			}
    		
    		
    		else
    		{
    			Toast toast = Toast.makeText(this, "Неверное количество товара", Toast.LENGTH_LONG);
    			toast.setGravity(Gravity.CENTER, 0, 0);
    			toast.show();
    			//Toast.makeText(this, QuantityItem.getText().toString()+"   "+getIntent().getExtras().getString("qua_item"), Toast.LENGTH_LONG).show();
    		}
    		}
    		else
    		{
    			Toast toast = Toast.makeText(this, "Неверное количество товара", Toast.LENGTH_LONG);
    			toast.setGravity(Gravity.CENTER, 0, 0);
    			toast.show();
    			//Toast.makeText(this, QuantityItem.getText().toString()+"   "+getIntent().getExtras().getString("qua_item"), Toast.LENGTH_LONG).show();
    		}
    				} else {
    					Toast toast = Toast.makeText(this, "Введите число", Toast.LENGTH_LONG);
    	    			toast.setGravity(Gravity.CENTER, 0, 0);
    	    			toast.show();
    				}
    		break;
    /*	case R.id.back_button_da:
    		if(Main.checkk==1)
			{
    			
			Intent itemfind = new Intent(this, Finder.class);
			Finder parentActivity = (Finder)getParent();
			parentActivity.replaceContentView("find", itemfind);
			} 
			else
			//if(Main.checkk==2)	
				
			{
    	//	Intent itemfind = new Intent(this, Finder.class);
    	//	Finder parentActivity = (Finder)getParent();
    	//	parentActivity.replaceContentView("find", itemfind);
		//	}
		//	else 
		//	{
				Intent itemfind = new Intent(this, Cats.class);
				Cats parentActivity = (Cats)getParent();
				itemfind.putExtra("Pid",cat_id);
				
				//startActivity(itemfind);
				//Main.tabHost.setCurrentTab(1);
				parentActivity.replaceContentView("find", itemfind);
				
				//Main.tabHost.setCurrentTab(3);
			}
    		break;*/
    	default:
    		break;
    	}
	}
	
/*	public void getDescription(String ItemId) {
		GetJSON json = new GetJSON();
		try {
			String gg = json.postData(ItemId, "", "QSearchItemById", "", this);
			JSONObject jsonObject = new JSONObject(gg);
			if(jsonObject.getString("error").equals("1")) {
				Toast.makeText(this, "Нет товара с таким кодом", Toast.LENGTH_LONG).show();
			} else {
				JSONArray jsonArray = new JSONArray(jsonObject.getString("items"));
				JSONObject jsonObject_1 = jsonArray.getJSONObject(0);
				Description.setText(jsonObject_1.getString("NAME")+"\n"+"ID: "+jsonObject_1.getString("ID"));
				Price.setText("Цена за шт: "+jsonObject_1.getString("PRICE"));
				Qua.setText(jsonObject_1.getString("QUANTITY"));
				id_item = jsonObject_1.getString("ID");
				price_item = jsonObject_1.getString("PRICE");
				qua_item = jsonObject_1.getString("QUANTITY");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}*/
	
	 public void replaceContentView(String id, Intent newIntent) {
		    //	View view = getLocalActivityManager().startActivity(id, newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView(); 
		    //	this.setContentView(view);

		    		View view = ((ActivityGroup)((Activity)this)).getLocalActivityManager()
		    	            .startActivity(id,
		    	                    newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
		    	            .getDecorView();
		        	((ActivityGroup)((Activity)this)).setContentView(view);
		    	
		    } 
	
	@Override
    public void onBackPressed() {
		if(Main.checkk==1)
		{
			
		Intent itemfind = new Intent(this, Finder.class);
		Finder parentActivity = (Finder)getParent();
		parentActivity.replaceContentView("find_ok", itemfind);
		} 
		else
		//if(Main.checkk==2)	
			
		{
	//	Intent itemfind = new Intent(this, Finder.class);
	//	Finder parentActivity = (Finder)getParent();
	//	parentActivity.replaceContentView("find", itemfind);
	//	}
	//	else 
	//	{
			Intent itemfind = new Intent(this, Cats.class);
			Cats parentActivity = (Cats)getParent();
			itemfind.putExtra("Pid",cat_id);
			parentActivity.replaceContentView("find", itemfind);
			
		//	startActivity(itemfind);
			//Main.tabHost.setCurrentTab(1);
		//	this.replaceContentView("find", itemfind);
			}
	/*	if(ItemDescription.act!="3")
		{
		Intent itemfind = new Intent(this, Finder.class);
		Finder parentActivity = (Finder)getParent();
		parentActivity.replaceContentView("find", itemfind);
		} else
		{
		Intent itemfind = new Intent(this, FinderName.class);
		FinderName parentActivity = (FinderName)getParent();
		parentActivity.replaceContentView("find", itemfind);
		}*/
    }
}